<template>
  <div class="app-container">
    <el-card class="card-header">
      <el-form>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="日期范围：">
              <el-date-picker style="width: 100%;" v-model="filterForm.dateRange" type="daterange" range-separator="至"
                start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="工单状态：">
              <el-select v-model="filterForm.workOrderStatus" placeholder="全部" style="width: 100%">
                <el-option label="全部" value="" />
                <el-option label="待处理" value="0" />
                <el-option label="处理中" value="1" />
                <el-option label="已完成" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="搜索：">
              <el-input v-model="filterForm.keyword" placeholder="请输入工单号或内容关键词" clearable>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-button  type="primary" @click="fetchWorkOrderList">搜索</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card class="mt-2">
      <el-button type="primary" :icon="Plus" @click="handleCreate">
        新建工单
      </el-button>
      <el-table :data="workOrderList" border style="width: 100%" v-loading="loading" class="mt-2">
        <el-table-column prop="workOrderNumber" label="工单编号" align="center" />
        <el-table-column prop="workOrderType" label="工单类型" align="center">
          <template #default="{ row }">
            <el-tag size="small">
              {{ showWorkOrderTypeList(row.workOrderType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="inspectionArea" label="巡检区域" align="center">
          <template #default="{ row }">
            {{ showInspectionAreaList(row.inspectionArea) }}
          </template>
        </el-table-column>
        <el-table-column prop="inspectionItems" label="检查内容" align="center" />
        <el-table-column prop="creationTime" label="创建时间" align="center" />
        <el-table-column prop="processingOperatorName" label="处理人" align="center" />
        <el-table-column prop="workOrderStatus" label="当前状态" align="center">
          <template #default="{ row }">
            <el-tag :type="statusTagType(row.workOrderStatus)" size="small">
              {{ statusText(row.workOrderStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right" align="center">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="handleView(row.id)">
              查看详情
            </el-button>
            <el-button type="text" size="small" @click="handleProcess(row)" v-if="row.workOrderStatus !== '2'">
              处理
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-row class="mt-2" justify="end">
        <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :total="pagination.total" :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper"
          @size-change="fetchWorkOrderList" @current-change="fetchWorkOrderList" />
      </el-row>
    </el-card>

    <!-- 新建巡检工单 -->
    <el-dialog v-model="showCreateDialog" title="新建巡检工单" width="50%">
      <el-form :model="newOrderForm" status-icon ref="showCreateDialogRef" :rules="newOrderFormRules"
        label-width="100px">
        <el-form-item label="工单类型" prop="workOrderType">
          <el-select v-model="newOrderForm.workOrderType" placeholder="请选择工单类型">
            <el-option v-for="type in workOrderTypes" :key="type.dictValue" :label="type.dictLabel"
              :value="type.dictValue" />
          </el-select>
        </el-form-item>

        <el-form-item label="巡检区域" prop="inspectionArea">
          <el-select v-model="newOrderForm.inspectionArea" placeholder="请选择巡检区域">
            <el-option v-for="area in inspectionAreas" :key="area.dictValue" :label="area.dictLabel"
              :value="area.dictValue" />
          </el-select>
        </el-form-item>

        <el-form-item label="检查内容" prop="inspectionItems">
          <el-input v-model="newOrderForm.inspectionItems" type="textarea" :rows="3" placeholder="请输入检查内容" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="createNewOrder">确定</el-button>
      </template>
    </el-dialog>

    <!-- 详情 -->
    <el-dialog :title="'工单详情 - ' + workOrderDetail.workOrderNumber" v-model="orderDetailVisible" width="800px">
      <!-- 基本信息卡片 -->
      <el-descriptions title="基本信息" :column="2" border>
        <el-descriptions-item label="工单编号">
          <span class="highlight-text">{{ workOrderDetail.workOrderNumber }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="工单类型">
          <el-tag type="info">{{ showWorkOrderTypeList(workOrderDetail.workOrderType) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="巡检区域">{{ workOrderDetail.inspectionArea }}</el-descriptions-item>
        <el-descriptions-item label="当前状态">
          <el-tag :type="statusTagType(workOrderDetail.workOrderStatus)">
            {{ statusText(workOrderDetail.workOrderStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ workOrderDetail.creationTime }}</el-descriptions-item>
        <el-descriptions-item label="处理人">
          <span class="highlight-text">{{ workOrderDetail.processingOperatorName || '未分配' }}</span>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 巡检内容卡片 -->
      <el-descriptions title="巡检内容" class="mt-2" :column="1" border>
        <el-descriptions-item label="检查内容" align="center">
          <div class="content-text">{{ workOrderDetail.inspectionItems }}</div>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 处理记录卡片 -->
      <h3 class="title">处理记录</h3>
      <el-steps direction="vertical">
        <el-step v-for="(log, index) in workOrderDetail.logList" :key="index" :title="log.operateTime">
          <template #description>
            <div>
              <div class="process-action">
                <el-tag type="success">{{ ['工单创建', '开始处理', '提交结果'][log.operate] }}</el-tag>
              </div>
              <div class="process-detail">{{ log.operateContent }}</div>
              <div class="process-operator">操作人：{{ log.operateName }}</div>
            </div>
          </template>
        </el-step>
      </el-steps>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="orderDetailVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleProcess(workOrderDetail)"
            v-if="workOrderDetail.workOrderStatus !== '2'">
            处理工单
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :title="'处理工单 - ' + processForm.workOrderNumber" v-model="processDialogVisible" width="600px">
      <el-form ref="processFormRef" :model="processForm" :rules="formRules" label-width="100px">
        <el-form-item label="工单状态" prop="workOrderStatus">
          <el-radio-group v-model="processForm.workOrderStatus">
            <el-radio-button label="1">开始处理</el-radio-button>
            <el-radio-button label="2">提交结果</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="处理内容" prop="processingNotes">
          <el-input v-model="processForm.solutionMeasures" type="textarea" :rows="4" placeholder="请输入处理内容" />
        </el-form-item>

        <el-form-item label="上传附件">
          <UploadFile v-model:file-ids="processForm.fileIds" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="processDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="submitProcessForm">确定处理</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { Search, Plus } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import UploadFile from '@/components/UploadFile';
import {
  listRunWorkOrder,
  getWorkOrderTypeList,
  getInspectionAreaList,
  getRunWorkOrderDetail,
  addRunWorkOrder,
  updateRunWorkOrder,
  handleRunWorkOrder
} from '@/api/prod_operate/prod_run/run_worder';

// 工单列表数据
const workOrderList = ref([]);
const loading = ref(false);
const orderDetailVisible = ref(false);
const workOrderDetail = ref({});

// 获取工单类型下拉列表
const workOrderTypes = ref([]);

// 筛选表单
const filterForm = reactive({
  dateRange: [],
  workOrderStatus: '',
  keyword: ''
});

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 状态标签类型
const statusTagType = (status) => {
  const map = {
    '0': 'warning',
    '1': 'primary',
    '2': 'success'
  };
  return map[status] || 'info';
};

// 状态文本
const statusText = (status) => {
  const map = {
    '0': '待处理',
    '1': '处理中',
    '2': '已完成'
  };
  return map[status] || '未知状态';
};

// 格式化时间显示
const formatTime = (timeStr) => {
  if (!timeStr) return '';
  const date = new Date(timeStr);
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
};


const showWorkOrderTypeList = (id) => {
  return workOrderTypes.value.find((item) => item.dictValue == id)?.dictLabel;
};
const showInspectionAreaList = (id) => {
  return inspectionAreas.value.find((item) => item.dictValue == id)?.dictLabel;
};

// 获取工单列表
const fetchWorkOrderList = async () => {
  try {
    loading.value = true;
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      keyword: filterForm.keyword,
      workOrderStatus: filterForm.workOrderStatus
    };

    if (filterForm.dateRange && filterForm.dateRange.length === 2) {
      params.startTime = filterForm.dateRange[0];
      params.endTime = filterForm.dateRange[1];
    }

    const res = await listRunWorkOrder(params);
    workOrderList.value = res.rows || [];
    pagination.total = res.total || 0;
  } catch (error) {
    console.error('获取工单列表失败:', error);
    ElMessage.error('获取工单列表失败');
  } finally {
    loading.value = false;
  }
};

// 获取工单详情
const fetchWorkOrderDetail = async (id) => {
  try {
    const res = await getRunWorkOrderDetail(id);
    workOrderDetail.value = res.data || {};
  } catch (error) {
    console.error('获取工单详情失败:', error);
    ElMessage.error('获取工单详情失败');
  }
};

const fetchWorkOrderTypes = async () => {
  try {
    const res = await getWorkOrderTypeList();
    workOrderTypes.value = res.data || [];
  } catch (error) {
    console.error('获取工单类型失败:', error);
    ElMessage.error('获取工单类型失败');
  }
};

// 获取巡检区域下拉列表
const inspectionAreas = ref([]);
const fetchInspectionAreas = async () => {
  try {
    const res = await getInspectionAreaList();
    inspectionAreas.value = res.data || [];
  } catch (error) {
    console.error('获取巡检区域失败:', error);
    ElMessage.error('获取巡检区域失败');
  }
};

// 新建工单对话框
const showCreateDialog = ref(false);
const showCreateDialogRef = ref();
const newOrderForm = reactive({
  workOrderType: '',
  inspectionArea: '',
  inspectionItems: ''
});

const newOrderFormRules = reactive({
  workOrderType: [
    { required: true, message: '请选择工单类型', trigger: 'change' }
  ],
  inspectionArea: [
    { required: true, message: '请选择巡检区域', trigger: 'change' }
  ],
  inspectionItems: [
    { required: true, message: '请输入检查内容', trigger: 'blur' }
  ]
});

// 处理工单对话框
const processDialogVisible = ref(false);
const processFormRef = ref();
const processForm = reactive({
  id: null,
  workOrderNumber: '',
  workOrderStatus: '1',
  solutionMeasures: '',
  fileIds: []
});

const formRules = reactive({
  workOrderStatus: [
    { required: true, message: '请选择处理动作', trigger: 'change' }
  ],
  solutionMeasures: [
    { required: true, message: '请输入处理内容', trigger: 'blur' },
    { min: 10, message: '处理内容至少10个字符', trigger: 'blur' }
  ]
});

// 操作处理函数
const handleCreate = () => {
  newOrderForm.workOrderType = '';
  newOrderForm.inspectionArea = '';
  newOrderForm.inspectionItems = '';
  showCreateDialog.value = true;
};

const handleView = async (id) => {
  await fetchWorkOrderDetail(id);
  orderDetailVisible.value = true;
};

const handleProcess = (row) => {
  processForm.id = row.id;
  processForm.workOrderNumber = row.workOrderNumber;
  processForm.workOrderStatus = row.workOrderStatus === '0' ? '1' : '2';
  processForm.solutionMeasures = '';
  processForm.fileIds = [];
  processDialogVisible.value = true;
};

// 创建新工单
const createNewOrder = async () => {
  try {
    await showCreateDialogRef.value.validate();

    await addRunWorkOrder(newOrderForm);

    ElMessage.success('工单创建成功');
    showCreateDialog.value = false;
    fetchWorkOrderList();
  } catch (error) {
    if (error !== 'validate') {
      console.error('创建工单失败:', error);
      ElMessage.error('工单创建失败');
    }
  }
};

// 提交处理表单
const submitProcessForm = async () => {
  try {
    await processFormRef.value.validate();

    const params = {
      id: processForm.id,
      action: processForm.workOrderStatus,
      solutionMeasures: processForm.solutionMeasures,
      fileIds: processForm.fileIds
    };

    await handleRunWorkOrder(params);

    ElMessage.success('工单处理成功');
    processDialogVisible.value = false;
    fetchWorkOrderList();

    if (orderDetailVisible.value) {
      await fetchWorkOrderDetail(processForm.id);
    }
  } catch (error) {
    if (error !== 'validate') {
      console.error('处理工单失败:', error);
      ElMessage.error('工单处理失败');
    }
  }
};

// 初始化数据
onMounted(() => {
  fetchWorkOrderList();
  fetchWorkOrderTypes();
  fetchInspectionAreas();
});
</script>

<style scoped>
.card-header :deep(.el-form-item) {
  margin-bottom: 0px;
}

.title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.process-item {
  width: 100%;
  text-align: left;
}

.highlight-text {
  color: #409EFF;
  font-weight: bold;
}

.content-text {
  padding: 10px;
  line-height: 1.5;
}

.process-time {
  font-size: 14px;
  color: #666;
}

.process-action {
  font-weight: bold;
  margin: 5px 0;
}

.process-detail {
  margin-bottom: 5px;
}

.process-operator {
  font-size: 12px;
  color: #999;
  margin-bottom: 20px;
}
</style>